import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {useRouter} from 'vue-router'

export const useTabsStore = defineStore('tabs', () => {
    const router = useRouter()
    console.log('Store tabs状态管理:::', router)
    const tabs = ref([{title: '参数信息', name: 'paramInfo'}])
    const activeTab = ref('paramInfo')

    //添加标签函数
    const addTab = (route) => {
        if (!tabs.value.some(t => t.name === route.name)) {
            tabs.value.push({title: route.title, name: route.name})
        }
        activeTab.value = route.name
    }

    const setActiveTab = (tabName) => {
        console.log("当前激活的标签：", tabName)
        activeTab.value = tabName
    }

    const closeTab = (tabName) => {
        console.log("要关闭的标签closeTab： ", tabName)
        const index = tabs.value.findIndex(t => t.name === tabName)
        console.log('关门标签的下标：', index, tabs)
        if (index !== -1) {
            tabs.value.splice(index, 1)
            if (activeTab.value === tabName) {
                const nextTab = tabs.value[index] || tabs.value[index - 1]
                console.log('nextTab', nextTab);
                if (nextTab) {
                    activeTab.value = nextTab.name
                    router.push({name: nextTab.name})
                    //如果删除的是最后一个tab标签
                } else {
                    activeTab.value = 'paramInfo'
                    router.push("/Dashboard")
                    console.log('删除的是最后一个===', router);
                    tabs.value.push({title: '首页', name: 'paramInfo'})
                }
            }
        }
    }

    return {
        tabs,
        activeTab,
        addTab,
        setActiveTab,
        closeTab
    }
})